package com.castile.secondkill.service.impl;

import com.castile.secondkill.controller.BaseController;
import com.castile.secondkill.dao.ItemDOMapper;
import com.castile.secondkill.dao.ItemStockDOMapper;
import com.castile.secondkill.dataobject.ItemDO;
import com.castile.secondkill.dataobject.ItemStockDO;
import com.castile.secondkill.error.EmBusinessError;
import com.castile.secondkill.exception.BusinessException;
import com.castile.secondkill.service.ItemService;
import com.castile.secondkill.service.PromoService;
import com.castile.secondkill.service.model.ItemModel;
import com.castile.secondkill.service.model.PromoModel;
import com.castile.secondkill.validator.ValidationResult;
import com.castile.secondkill.validator.ValidatorImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务实现
 *
 * @author Hongliang Zhu
 * @create 2023-03-05 23:32
 */
@Service
public class ItemServiceImpl implements ItemService {
    private static final Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

    @Autowired
    private ItemDOMapper itemDOMapper;
    @Autowired
    private ItemStockDOMapper itemStockDOMapper;
    @Autowired
    private ValidatorImpl validator;

    @Autowired
    private PromoService promoService;

    @Override
    @Transactional
    public ItemModel createItem(ItemModel itemModel) throws BusinessException {
        // 校验
        ValidationResult validationResult = validator.validate(itemModel);
        if (validationResult.isHasError()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATIONERROR, validationResult.getErrorMsg());
        }
        // itemModel --> itemDO之间的转换
        ItemDO itemDO = convertItemDoFrom(itemModel);
        if (itemDO == null) {
            return null;
        }
        // 调用DAO层插入数据
        itemDOMapper.insertSelective(itemDO);
        // 设置id， 因为insertSelective会将id重新赋值到itemDO中
        itemModel.setId(itemDO.getId());
        // 库存表插入
        ItemStockDO itemStockDO = convertItemStockFrom(itemModel);
        // 调用DAO层插入数据
        itemStockDOMapper.insertSelective(itemStockDO);
        // 返回创建完成的对象
        return getItem(itemModel.getId());
    }

    private ItemStockDO convertItemStockFrom(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemStockDO itemStockDO = new ItemStockDO();
        itemStockDO.setItemId(itemModel.getId());
        itemStockDO.setStock(itemModel.getStock());
        return itemStockDO;
    }

    private ItemDO convertItemDoFrom(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemDO itemDO = new ItemDO();

        BeanUtils.copyProperties(itemModel, itemDO);
        // 设置价格
        itemDO.setPrice(itemModel.getPrice().doubleValue());
        return itemDO;
    }

    @Override
    public List<ItemModel> listItem() {
        List<ItemDO> itemDOS = itemDOMapper.listItem();
        return itemDOS.stream().map(itemDO -> {
            ItemStockDO itemStockDO = itemStockDOMapper.selectByItemId(itemDO.getId());
            return convertItemModelFrom(itemDO, itemStockDO);
        }).collect(Collectors.toList());
    }

    @Override
    public ItemModel getItem(Integer id) {
        ItemDO itemDO = itemDOMapper.selectByPrimaryKey(id);
        if (itemDO == null) {
            return null;
        }
        // 操作获得库存数量
        ItemStockDO itemStockDO = itemStockDOMapper.selectByItemId(itemDO.getId());
        // 将DO转换成Model
        ItemModel itemModel = convertItemModelFrom(itemDO, itemStockDO);
        // 获取活动商品信息
        PromoModel promoModel = promoService.getPromoByItemId(itemModel.getId());

        // 当秒杀活动没有结束时，需要设置商品的活动
        if(promoModel != null && promoModel.getStatus() != 3){
//            logger.warn("查找到商品{}有秒杀活动！", itemModel.getTitle());
            itemModel.setPromoModel(promoModel);
        }

        return itemModel;
    }

    private ItemModel convertItemModelFrom(ItemDO itemDO, ItemStockDO itemStockDO) {
        if (itemStockDO == null) {
            return null;
        }
        ItemModel itemModel = new ItemModel();
        BeanUtils.copyProperties(itemDO, itemModel);
        itemModel.setPrice(new BigDecimal(itemDO.getPrice()));
        itemModel.setStock(itemStockDO.getStock());
        return itemModel;
    }

    @Override
    @Transactional
    public boolean decreaseStock(Integer itemId, Integer amount) {
        int rows = itemStockDOMapper.decreaseStock(itemId, amount);
        // 更新库存成功
        return rows > 0;
    }

    @Override
    @Transactional
    public void increaseSales(Integer itemId, Integer amount) {
        itemDOMapper.increaseSales(itemId, amount);
    }
}
